package com.shiro.web.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.shiro.utils.Hash;
import com.shiro.web.service.UserService;

@Controller
public class LoginController {

	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	public ModelAndView login(String username, String password,
			HttpSession session) {
		ModelAndView model = new ModelAndView();
		Subject current = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username,
				Hash.md5(password), true);
		try {
			current.login(token);
		} catch (AuthenticationException e) {
			model.addObject("message", e.getMessage());
			model.setViewName("/login");
		}

		if (current.isAuthenticated()) {
			session.setAttribute("user", userService.findUserByName(username));
			model.setViewName("/success");
		}
		return model;
	}

	@RequestMapping("logout")
	public String logout() {
		Subject current = SecurityUtils.getSubject();
		current.logout();
		return "/login";
	}
}
